package com.example.xgsweather.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.xgsweather.R;
import com.example.xgsweather.activity.WeatherFragmentActivity;
import com.example.xgsweather.db.FrequentlyUsedCity;
import com.example.xgsweather.util.LogUtil;
import com.qweather.sdk.bean.base.Code;
import com.qweather.sdk.bean.weather.WeatherNowBean;
import com.qweather.sdk.view.QWeather;

import org.litepal.LitePal;

import java.util.List;

public class CitiesAdapter extends RecyclerView.Adapter<CitiesAdapter.ViewHolder> {

    private static final String TAG = "CitiesAdapter测试";
    private static final int TYPE_DEL_VIEW = 0;
    private static final int TYPE_NORMAL_VIEW = 1;

    private boolean isDelMod;
    private Activity mActivity;
    private List<FrequentlyUsedCity> mFrequentlyUsedCityList;

    public CitiesAdapter(List<FrequentlyUsedCity> mFrequentlyUsedCityList, Activity activity, boolean isDelMod) {
        this.mFrequentlyUsedCityList = mFrequentlyUsedCityList;
        this.mActivity = activity;
        this.isDelMod = isDelMod;
    }

    public void setDelMode(boolean isDelMod) {
        LogUtil.d("setDelMode");
        this.isDelMod = isDelMod;
    }

    @Override
    public com.example.xgsweather.adapter.CitiesAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LogUtil.d("onCreateViewHolder");
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_city_list, parent, false);
        ViewHolder holder = new ViewHolder(view);
        if (viewType == TYPE_DEL_VIEW) {
            holder.delButton.setVisibility(View.VISIBLE);
        } else if (viewType == TYPE_NORMAL_VIEW) {
            holder.delButton.setVisibility(View.GONE);
        }
        holder.frequentlyUsedCityView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                FrequentlyUsedCity frequentlyUsedCity = mFrequentlyUsedCityList.get(position);
                Intent intent = new Intent(mActivity, WeatherFragmentActivity.class);
                intent.putExtra("weather_id", frequentlyUsedCity.getWeatherId());
                intent.putExtra("county_name", frequentlyUsedCity.getCityName());
                intent.putExtra("position", position);
                mActivity.startActivity(intent);
                mActivity.finish();
            }
        });
        holder.delButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                FrequentlyUsedCity frequentlyUsedCity = mFrequentlyUsedCityList.get(position);
                int result = LitePal.deleteAll(FrequentlyUsedCity.class, "weatherId = ? and cityName = ?", frequentlyUsedCity.getWeatherId(), frequentlyUsedCity.getCityName());
                LogUtil.w("删除数据：" + result);
                mFrequentlyUsedCityList = LitePal.findAll(FrequentlyUsedCity.class);
                notifyDataSetChanged();
            }
        });
        return holder;
    }

    /**
     * 用于对 RecyclerView子项的数据进行赋值，会在每个子项被滚动到屏幕内的时候执行
     */
    @Override
    public void onBindViewHolder(@NonNull CitiesAdapter.ViewHolder holder, int position) {
        LogUtil.d("onBindViewHolder");
        FrequentlyUsedCity frequentlyUsedCity = mFrequentlyUsedCityList.get(position);
        holder.cityNameTv.setText(frequentlyUsedCity.getCityName());
        // 查询当前天气
        QWeather.getWeatherNow(mActivity.getApplication(), frequentlyUsedCity.getWeatherId(), new QWeather.OnResultWeatherNowListener() {
            @Override
            public void onError(Throwable e) {
                LogUtil.w(TAG + " getWeather onError: " + e);
            }

            @Override
            public void onSuccess(WeatherNowBean weatherBean) {
                //先判断返回的status是否正确，当status正确时获取数据，若status不正确，可查看status对应的Code值找到原因
                if (Code.OK == weatherBean.getCode()) {
                    WeatherNowBean.NowBaseBean now = weatherBean.getNow();
                    mActivity.runOnUiThread(new Runnable() {
                        @SuppressLint("SetTextI18n")
                        @Override
                        public void run() {
                            holder.cityTemperatureTv.setText(now.getTemp() + "℃");
                            holder.cityWeatherInfoTv.setText(now.getText());
                        }
                    });
                } else {
                    //在此查看返回数据失败的原因
                    Code code = weatherBean.getCode();
                    LogUtil.w(TAG + "WeatherActivity failed code: " + code);
                }
            }
        });
    }

    /**
     * 用于告诉RecyclerView一共有多少子项
     *
     * @return 返回数据源的长度
     */
    @Override
    public int getItemCount() {
        return mFrequentlyUsedCityList.size();
    }

    @Override
    public int getItemViewType(int position) {
        LogUtil.d("getItemViewType");
        return isDelMod ? TYPE_DEL_VIEW : TYPE_NORMAL_VIEW;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView cityNameTv;
        TextView cityTemperatureTv;
        TextView cityWeatherInfoTv;
        ImageView delButton;
        // 子项最外层布局的实例
        View frequentlyUsedCityView;

        public ViewHolder(View view) {
            super(view);
            frequentlyUsedCityView = view;
            cityNameTv = view.findViewById(R.id.city_name);
            cityTemperatureTv = view.findViewById(R.id.city_temperature);
            cityWeatherInfoTv = view.findViewById(R.id.city_weather_info);
            delButton = view.findViewById(R.id.bt_del);
        }
    }

}
